//go:build !windows
// +build !windows

package gui

import (
	"fmt"
	"mcp-clarification-service/internal/config"
	"mcp-clarification-service/internal/tools"
	"sync"
	"time"

	"fyne.io/fyne/v2"
	"fyne.io/fyne/v2/app"
	"fyne.io/fyne/v2/container"
	"fyne.io/fyne/v2/dialog"
	"fyne.io/fyne/v2/layout"
	"fyne.io/fyne/v2/theme"
	"fyne.io/fyne/v2/widget"
)

// Manager GUI管理器
type Manager struct {
	app    fyne.App
	config *config.GUIConfig
	mu     sync.Mutex
	active bool
}

// NewManager 创建新的GUI管理器
func NewManager(cfg *config.GUIConfig) *Manager {
	a := app.New()

	// 预热：创建并立即隐藏一个窗口
	w := a.NewWindow("Warmup")
	w.Resize(fyne.NewSize(1, 1))
	w.Hide()

	return &Manager{
		app:    a,
		config: cfg,
	}
}

// ShowQuestions 显示问题窗口
func (m *Manager) ShowQuestions(questions []tools.Question, timeout time.Duration) ([]tools.Answer, bool, error) {
	m.mu.Lock()
	if m.active {
		m.mu.Unlock()
		return nil, false, fmt.Errorf("another window is active")
	}
	m.active = true
	m.mu.Unlock()

	defer func() {
		m.mu.Lock()
		m.active = false
		m.mu.Unlock()
	}()

	// 根据问题数量调整窗口大小
	width := float32(m.config.WindowWidth)
	height := float32(m.config.WindowHeight)
	if len(questions) == 1 {
		width = 500
		height = 400
	} else {
		width = 700
		height = 550
	}

	// 创建窗口
	title := "AI 问题澄清"
	if len(questions) > 1 {
		title = fmt.Sprintf("AI 问题澄清 (共 %d 题)", len(questions))
	}
	w := m.app.NewWindow(title)
	w.Resize(fyne.NewSize(width, height))
	w.CenterOnScreen()

	// 结果通道
	resultCh := make(chan []tools.Answer, 1)
	cancelledCh := make(chan bool, 1)

	// 单个问题的简单实现
	if len(questions) == 1 {
		q := questions[0]
		content := m.createQuestionContent(q, w, func(answer tools.Answer) {
			resultCh <- []tools.Answer{answer}
			w.Close()
		}, func() {
			cancelledCh <- true
			w.Close()
		})

		w.SetContent(content)
	} else {
		// 多个问题使用标签页
		tabs := m.createTabs(questions, w, func(answers []tools.Answer) {
			resultCh <- answers
			w.Close()
		}, func() {
			cancelledCh <- true
			w.Close()
		})

		w.SetContent(tabs)
	}

	// 键盘快捷键
	w.Canvas().SetOnTypedKey(func(key *fyne.KeyEvent) {
		if key.Name == fyne.KeyEscape {
			cancelledCh <- true
			w.Close()
		}
	})

	// 超时处理（timeout <= 0 表示不限制时间）
	if timeout > 0 {
		timer := time.AfterFunc(timeout, func() {
			cancelledCh <- true
			w.Close()
		})
		defer timer.Stop()
	}

	// 显示窗口（不阻塞）
	w.Show()

	// 等待结果
	select {
	case answers := <-resultCh:
		return answers, false, nil
	case <-cancelledCh:
		return nil, true, nil
	}
}

// createQuestionContent 创建问题内容
func (m *Manager) createQuestionContent(q tools.Question, w fyne.Window, onSubmit func(tools.Answer), onCancel func()) fyne.CanvasObject {
	// 问题标题 - 使用粗体大字
	questionLabel := widget.NewRichTextFromMarkdown("## " + q.Question)
	questionLabel.Wrapping = fyne.TextWrapWord

	var answerWidget fyne.CanvasObject
	var getAnswer func() tools.Answer
	var validateAnswer func() error
	var firstFocusable fyne.Focusable

	switch q.Type {
	case "single":
		radio := widget.NewRadioGroup(q.Options, nil)
		answerWidget = container.NewVBox(
			layout.NewSpacer(),
			radio,
			layout.NewSpacer(),
		)
		getAnswer = func() tools.Answer {
			idx := -1
			for i, opt := range q.Options {
				if opt == radio.Selected {
					idx = i
					break
				}
			}
			return tools.Answer{
				ID:            q.ID,
				Type:          q.Type,
				SelectedIndex: &idx,
			}
		}
		validateAnswer = func() error {
			if radio.Selected == "" {
				return fmt.Errorf("请选择一个选项")
			}
			return nil
		}

	case "multiple":
		checks := make([]*widget.Check, len(q.Options))
		checkContainer := container.NewVBox()
		for i, opt := range q.Options {
			checks[i] = widget.NewCheck(opt, nil)
			checkContainer.Add(checks[i])
		}
		answerWidget = container.NewVBox(
			layout.NewSpacer(),
			checkContainer,
			layout.NewSpacer(),
		)
		if len(checks) > 0 {
			firstFocusable = checks[0]
		}
		getAnswer = func() tools.Answer {
			indices := []int{}
			for i, check := range checks {
				if check.Checked {
					indices = append(indices, i)
				}
			}
			return tools.Answer{
				ID:              q.ID,
				Type:            q.Type,
				SelectedIndices: indices,
			}
		}
		validateAnswer = func() error {
			hasChecked := false
			for _, check := range checks {
				if check.Checked {
					hasChecked = true
					break
				}
			}
			if !hasChecked {
				return fmt.Errorf("请至少选择一个选项")
			}
			return nil
		}

	case "free_text":
		entry := widget.NewMultiLineEntry()
		entry.SetPlaceHolder(q.Placeholder)
		entry.Wrapping = fyne.TextWrapWord
		answerWidget = container.NewVBox(
			layout.NewSpacer(),
			entry,
			layout.NewSpacer(),
		)
		firstFocusable = entry
		getAnswer = func() tools.Answer {
			return tools.Answer{
				ID:   q.ID,
				Type: q.Type,
				Text: entry.Text,
			}
		}
		validateAnswer = func() error {
			// 简答题允许空答案
			return nil
		}
	}

	// 补充说明
	additionalLabel := widget.NewLabel("💬 补充说明（可选）")
	additionalEntry := widget.NewEntry()
	additionalEntry.SetPlaceHolder("如有需要，可在此添加补充说明...")

	// 提交逻辑
	handleSubmit := func() {
		if err := validateAnswer(); err != nil {
			dialog.ShowError(err, w)
			return
		}
		answer := getAnswer()
		answer.AdditionalInput = additionalEntry.Text
		m.showConfirmationDialog(w, []tools.Question{q}, []tools.Answer{answer}, func() {
			onSubmit(answer)
		})
	}

	// 按钮 - 使用图标
	submitBtn := widget.NewButtonWithIcon("提交答案", theme.ConfirmIcon(), handleSubmit)
	submitBtn.Importance = widget.HighImportance

	cancelBtn := widget.NewButtonWithIcon("取消", theme.CancelIcon(), onCancel)

	buttons := container.NewHBox(
		layout.NewSpacer(),
		cancelBtn,
		submitBtn,
	)

	// 组装内容 - 添加间距
	content := container.NewVBox(
		questionLabel,
		widget.NewSeparator(),
		answerWidget,
		widget.NewSeparator(),
		additionalLabel,
		additionalEntry,
		layout.NewSpacer(),
		buttons,
	)

	// 设置焦点
	if firstFocusable != nil {
		w.Canvas().Focus(firstFocusable)
	}

	// Enter键提交（仅对单选和多选有效）
	if q.Type != "free_text" {
		w.Canvas().SetOnTypedKey(func(key *fyne.KeyEvent) {
			if key.Name == fyne.KeyReturn || key.Name == fyne.KeyEnter {
				handleSubmit()
			} else if key.Name == fyne.KeyEscape {
				onCancel()
			}
		})
	}

	return container.NewPadded(content)
}

// createTabs 创建多标签页
func (m *Manager) createTabs(questions []tools.Question, w fyne.Window, onSubmit func([]tools.Answer), onCancel func()) fyne.CanvasObject {
	// 存储每个问题的答案获取函数和验证函数
	getAnswerFuncs := make([]func() tools.Answer, len(questions))
	validateFuncs := make([]func() error, len(questions))
	isAnsweredFuncs := make([]func() bool, len(questions))
	tabs := container.NewAppTabs()

	progressLabel := widget.NewLabel("")
	progressLabel.TextStyle = fyne.TextStyle{Bold: true}
	progressBar := widget.NewProgressBar()
	progressBar.Min = 0
	progressBar.Max = float64(len(questions))

	var updateProgress func()
	onChanged := func() {
		if updateProgress != nil {
			updateProgress()
		}
	}

	// 创建每个问题的标签页
	for i, q := range questions {
		idx := i
		tabTitle := fmt.Sprintf("问题 %d", i+1)

		content, getAnswer, validate, isAnswered := m.createTabQuestionContent(q, w, onChanged)
		getAnswerFuncs[idx] = getAnswer
		validateFuncs[idx] = validate
		isAnsweredFuncs[idx] = isAnswered

		tabs.Append(container.NewTabItem(tabTitle, content))
	}

	updateProgress = func() {
		answered := 0
		for _, f := range isAnsweredFuncs {
			if f != nil && f() {
				answered++
			}
		}
		progressLabel.SetText(fmt.Sprintf("📊 进度: %d/%d (可随时切换标签页修改答案)", answered, len(questions)))
		progressBar.SetValue(float64(answered))
	}
	updateProgress()

	// 导航按钮
	prevBtn := widget.NewButtonWithIcon("上一题", theme.NavigateBackIcon(), func() {
		if tabs.SelectedIndex() > 0 {
			tabs.SelectIndex(tabs.SelectedIndex() - 1)
		}
	})

	nextBtn := widget.NewButtonWithIcon("下一题", theme.NavigateNextIcon(), func() {
		if tabs.SelectedIndex() < len(questions)-1 {
			tabs.SelectIndex(tabs.SelectedIndex() + 1)
		}
	})

	// 提交所有答案按钮
	submitAllBtn := widget.NewButtonWithIcon("提交所有答案", theme.ConfirmIcon(), func() {
		answers := make([]tools.Answer, len(questions))
		for i := 0; i < len(questions); i++ {
			if err := validateFuncs[i](); err != nil {
				dialog.ShowError(fmt.Errorf("问题 %d: %s", i+1, err.Error()), w)
				tabs.SelectIndex(i)
				return
			}
			answers[i] = getAnswerFuncs[i]()
		}
		m.showConfirmationDialog(w, questions, answers, func() {
			onSubmit(answers)
		})
	})
	submitAllBtn.Importance = widget.HighImportance

	cancelBtn := widget.NewButtonWithIcon("取消", theme.CancelIcon(), onCancel)

	// 提示信息
	hintLabel := widget.NewLabel("💡 提示：可以随时切换标签页修改答案，最后统一提交")
	hintLabel.TextStyle = fyne.TextStyle{Italic: true}

	progressContainer := container.NewVBox(progressLabel, progressBar)

	// 底部控制栏
	navButtons := container.NewHBox(
		prevBtn,
		nextBtn,
		layout.NewSpacer(),
		progressContainer,
	)

	submitButtons := container.NewHBox(
		layout.NewSpacer(),
		cancelBtn,
		submitAllBtn,
	)

	bottomBar := container.NewVBox(
		widget.NewSeparator(),
		hintLabel,
		navButtons,
		submitButtons,
	)

	return container.NewBorder(nil, bottomBar, nil, nil, tabs)
}

func (m *Manager) showConfirmationDialog(w fyne.Window, questions []tools.Question, answers []tools.Answer, onConfirm func()) {
	items := make([]fyne.CanvasObject, 0, len(questions))
	for i, q := range questions {
		title := widget.NewLabel(fmt.Sprintf("问题 %d：%s", i+1, q.Question))
		title.TextStyle = fyne.TextStyle{Bold: true}

		answerLabel := widget.NewLabel(formatAnswerSummaryText(q, answers[i]))
		answerLabel.Wrapping = fyne.TextWrapWord

		items = append(items, container.NewVBox(title, answerLabel, widget.NewSeparator()))
	}

	content := container.NewVBox(items...)
	scroll := container.NewVScroll(content)
	scroll.SetMinSize(fyne.NewSize(500, 300))

	dialog.NewCustomConfirm(
		"确认提交",
		"确认提交",
		"返回修改",
		scroll,
		func(confirm bool) {
			if confirm && onConfirm != nil {
				onConfirm()
			}
		},
		w,
	).Show()
}

// createTabQuestionContent 创建标签页中的问题内容（返回获取答案、验证函数及完成状态）
func (m *Manager) createTabQuestionContent(q tools.Question, w fyne.Window, onChanged func()) (fyne.CanvasObject, func() tools.Answer, func() error, func() bool) {
	questionLabel := widget.NewRichTextFromMarkdown("## " + q.Question)
	questionLabel.Wrapping = fyne.TextWrapWord

	var answerWidget fyne.CanvasObject
	var getAnswer func() tools.Answer
	var validateAnswer func() error
	var isAnswered func() bool

	if onChanged == nil {
		onChanged = func() {}
	}

	switch q.Type {
	case "single":
		radio := widget.NewRadioGroup(q.Options, nil)
		radio.OnChanged = func(string) {
			onChanged()
		}
		answerWidget = container.NewVBox(
			layout.NewSpacer(),
			radio,
			layout.NewSpacer(),
		)
		getAnswer = func() tools.Answer {
			idx := -1
			for i, opt := range q.Options {
				if opt == radio.Selected {
					idx = i
					break
				}
			}
			return tools.Answer{
				ID:            q.ID,
				Type:          q.Type,
				SelectedIndex: &idx,
			}
		}
		validateAnswer = func() error {
			if radio.Selected == "" {
				return fmt.Errorf("请选择一个选项")
			}
			return nil
		}
		isAnswered = func() bool {
			return radio.Selected != ""
		}

	case "multiple":
		checks := make([]*widget.Check, len(q.Options))
		checkContainer := container.NewVBox()
		for i, opt := range q.Options {
			checks[i] = widget.NewCheck(opt, func(bool) {
				onChanged()
			})
			checkContainer.Add(checks[i])
		}
		answerWidget = container.NewVBox(
			layout.NewSpacer(),
			checkContainer,
			layout.NewSpacer(),
		)
		getAnswer = func() tools.Answer {
			indices := []int{}
			for i, check := range checks {
				if check.Checked {
					indices = append(indices, i)
				}
			}
			return tools.Answer{
				ID:              q.ID,
				Type:            q.Type,
				SelectedIndices: indices,
			}
		}
		validateAnswer = func() error {
			hasChecked := false
			for _, check := range checks {
				if check.Checked {
					hasChecked = true
					break
				}
			}
			if !hasChecked {
				return fmt.Errorf("请至少选择一个选项")
			}
			return nil
		}
		isAnswered = func() bool {
			for _, check := range checks {
				if check.Checked {
					return true
				}
			}
			return false
		}

	case "free_text":
		entry := widget.NewMultiLineEntry()
		entry.SetPlaceHolder(q.Placeholder)
		entry.Wrapping = fyne.TextWrapWord
		entry.OnChanged = func(string) {
			onChanged()
		}
		answerWidget = container.NewVBox(
			layout.NewSpacer(),
			entry,
			layout.NewSpacer(),
		)
		getAnswer = func() tools.Answer {
			return tools.Answer{
				ID:   q.ID,
				Type: q.Type,
				Text: entry.Text,
			}
		}
		validateAnswer = func() error {
			return nil
		}
		isAnswered = func() bool {
			return true
		}
	}

	content := container.NewVBox(
		questionLabel,
		widget.NewSeparator(),
		answerWidget,
	)

	return container.NewPadded(content), getAnswer, validateAnswer, isAnswered
}

// IsActive 检查是否有活动窗口
func (m *Manager) IsActive() bool {
	m.mu.Lock()
	defer m.mu.Unlock()
	return m.active
}

// Run 运行Fyne应用（阻塞）
func (m *Manager) Run() {
	m.app.Run()
}
